﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;
using Microsoft.Practices.Unity;
using PicStore.BLL.Interface;
using PicStore.DAL;
using PicStore.Model;
using PicStore.Web.Lib;
using PicStore.Web.Models.Report;
using HelpChart = System.Web.Helpers.Chart;

namespace PicStore.Web.Controllers
{
    public class ReportController : BaseController
    {
        [Dependency]
        public IReportService ReportService { get; set; }

        [Dependency]
        public ICategoryService CategoryService { get; set; }

        public ActionResult Index()
        {
            ReportModel model = new ReportModel();
            var categories = CategoryService.GetBaseCategoryListForAdmin();
            model.CategoryList = Utility.GetCategoryList(categories);
            model.MonthList = Utility.GetMonthList();
            model.ReportTable = new List<ReportItem>();
            model.ReportImageNames = new List<string>();

            return View(model);
        }

        public ActionResult GetReport(ReportModel model)
        {
            if (model.CategoryId == 0)
            {
                return Redirect("index");
            }
            BaseCategoryEnum baseCategory = (BaseCategoryEnum) model.CategoryId;
            var categories = CategoryService.GetBaseCategoryListForAdmin();
            model.CategoryList = Utility.GetCategoryList(categories);
            model.MonthList = Utility.GetMonthList();
            model.ReportTable = ReportService.GetFrontReportSpecial(baseCategory, model.Month);
            model.ReportImageNames = ChartView(baseCategory.ToString(), model.ReportTable);

            return View("Index", model);
        }

        public List<string> ChartView(string reportName, List<ReportItem> reportTable)
        {
            int upLimit = 10;
            int itemNumberForEachChart = 8;

            var yearList = reportTable.Select(c => c.Year).Distinct().OrderBy(c => c);
            var categoryItemList = reportTable.Select(c => c.CategoryItemName).Distinct();
            int areaCount = 1;
            int categoryItemCount = categoryItemList.Count();
            if (categoryItemCount > upLimit)
            {
                areaCount = (categoryItemCount / itemNumberForEachChart) + 1;
            }

            List<string> fileList = new List<string>();
            for (int i = 0; i < areaCount; i++)
            {
                int takeCount = itemNumberForEachChart;
                if (i == (areaCount - 1) && areaCount > 1)
                {
                    takeCount = categoryItemCount%itemNumberForEachChart;
                }
                else if (areaCount == 1)
                {
                    takeCount = categoryItemCount;
                }
                var subItems = categoryItemList.Skip(i * itemNumberForEachChart).Take(takeCount);

                using (Chart chart = new Chart())
                {
                    #region prepare the chart file

                    chart.Width = 1200;
                    chart.Height = 800;
                    chart.RenderType = RenderType.BinaryStreaming;
                    chart.Palette = ChartColorPalette.Bright;

                    string areaName = i.ToString();

                    chart.ChartAreas.Add(areaName);
                    chart.ChartAreas[0].AxisX.Interval = 1;
                    // Show chart with right-angled axes
                    chart.ChartAreas[0].Area3DStyle.IsRightAngleAxes = true;

                    // Show columns as clustered
                    chart.ChartAreas[0].Area3DStyle.IsClustered = true;

                    // Show X axis end labels
                    chart.ChartAreas[0].AxisX.LabelStyle.IsEndLabelVisible = true;

                    // Set rotational angles
                    chart.ChartAreas[0].Area3DStyle.Inclination = 30;
                    chart.ChartAreas[0].Area3DStyle.Inclination = 30;
                    chart.ChartAreas[0].Area3DStyle.Enable3D = true;
                    Font font = new Font("Trebuchet MS", (float)12, FontStyle.Bold);
                    chart.ChartAreas[0].AxisX.TitleFont = font;
                    chart.ChartAreas[0].AxisX.TitleForeColor = Color.Blue;

                    // Disable auto-fitting of the legend text
                    chart.Legends.Add(new Legend());

                    if (areaCount > 0)
                    {
                        chart.ChartAreas[0].AxisY.Minimum = 0;
                        chart.ChartAreas[0].AxisY.Maximum = 100;
                    }

                    foreach (var currentYear in yearList)
                    {
                        string year = currentYear.ToString();
                        chart.Series.Add(year);
                        var ser = chart.Series[year];

                        ser.ChartArea = areaName;
                        ser.ChartType = SeriesChartType.Column;
                        ser["LabelStyle"] = "Top";
                        ser["PointWidth"] = "0.6";
                        ser.IsVisibleInLegend = true;
                        ser.Font = new Font("Trebuchet MS", 8, FontStyle.Bold);

                        foreach (var category in subItems)
                        {
                            var item = (from c in reportTable
                                        where c.Year == currentYear && c.CategoryItemName == category
                                        select c).FirstOrDefault();

                            DataPoint point = new DataPoint();
                            string xValue = category;
                            point.AxisLabel = category;
                            double yValue = 0;
                            if (item != null)
                            {
                                decimal value = item.Value;
                                point.Label = item.PercentValue;
                                yValue = (double) value;
                            }
                            else
                            {
                                point.Label = "0%";
                                yValue = 0;
                            }
                            point.SetValueXY(xValue, yValue);

                            ser.Points.Add(point);
                        }
                    }
                    #endregion

                    string pathFirstPart = HttpRuntime.AppDomainAppPath +
                                           ConfigurationManager.AppSettings["DownloadFolder"];
                    string subPath = PictureHelper.GetPhysicalSubPath(pathFirstPart, "ReportChart");

                    string relativePath = ConfigurationManager.AppSettings["DownloadFolder"] + subPath + "/";
                    string chartTitle = reportName;
                    var relativeFileName = string.Format("{0}{1}_{2}.jpg", relativePath, chartTitle, DateTime.Now.Ticks);
                    var physicalFile = Server.MapPath(relativeFileName);


                    if (System.IO.File.Exists(physicalFile))
                    {
                        // Always overwrite the image.
                        System.IO.File.Delete(physicalFile);
                    }
                    chart.SaveImage(physicalFile, ChartImageFormat.Jpeg);

                    fileList.Add(relativeFileName);
                }
            }

            return fileList;
        }
    }
}
